import React from 'react';
import { createRoot } from 'react-dom/client';
import Modal from "./Modal";


export default class PopupManager {
    private container: HTMLDivElement | null = null;
    constructor() {
        this.initContainer()
    }
    
    // 初始化容器
    private initContainer() {
        // 如果没有popupContainer
        if (!this.container) {
            this.container = document.createElement('div');
            this.container.id = 'modal-container';
            this.container.style.position = 'fixed';
            this.container.style.bottom = '1rem';
            this.container.style.right = '1rem';
            this.container.style.zIndex = '1060';
            document.body.appendChild(this.container);
        }
    }

    open(args: { title: string, body: React.ReactNode, footer?: React.ReactNode }) {
        // Create a div for this specific toast
        const modalId = `modal-${Date.now()}`;
        const modalElement = document.createElement('div');
        modalElement.id = modalId;
        if (this.container) {
            this.container.appendChild(modalElement);
        }
          // Create root for this toast
        const root = createRoot(modalElement);
        root.render(React.createElement(Modal, {
            title: args.title,
            body: args.body,
            footer: args.footer,
            onClose: () => this.onClose(root, modalId),
        }));

        return {
            hide: () => {
                this.onClose(root, modalId);
            }
        };
    }
    
    private onClose(root: any, modalId: string) {
        const element = document.getElementById(modalId);
        if (element) {
            root.unmount();
            element.remove();
        }
    }
}